
import android.annotation.SuppressLint
import android.widget.Toast
import androidx.activity.compose.BackHandler
import androidx.compose.animation.ExperimentalSharedTransitionApi
import androidx.compose.animation.animateBounds
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.MarqueeAnimationMode
import androidx.compose.foundation.MarqueeDefaults.Velocity
import androidx.compose.foundation.background
import androidx.compose.foundation.basicMarquee
import androidx.compose.foundation.focusable
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.requiredSize
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.QueueMusic
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.PlayCircleOutline
import androidx.compose.material.icons.filled.Repeat
import androidx.compose.material.icons.filled.RepeatOne
import androidx.compose.material.icons.filled.Shuffle
import androidx.compose.material.icons.outlined.ArrowBackIosNew
import androidx.compose.material.icons.outlined.Pause
import androidx.compose.material.icons.outlined.PlayArrow
import androidx.compose.material.icons.outlined.SkipNext
import androidx.compose.material.icons.outlined.SkipPrevious
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.movableContentWithReceiverOf
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.draw.blur
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.PointerEvent
import androidx.compose.ui.input.pointer.PointerInputChange
import androidx.compose.ui.input.pointer.changedToUpIgnoreConsumed
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.LookaheadScope
import androidx.compose.ui.layout.onPlaced
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.util.fastAll
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.lifecycle.repeatOnLifecycle
import androidx.media3.common.C
import androidx.media3.common.Player
import coil3.compose.AsyncImage
import com.chenxinzhimusic.R
import com.chenxinzhimusic.api.Api
import com.chenxinzhimusic.data.loveKey
import com.chenxinzhimusic.entity.MusicInfo
import com.chenxinzhimusic.entity.PlayList
import com.chenxinzhimusic.entity.addToLove
import com.chenxinzhimusic.entity.getMusic
import com.chenxinzhimusic.entity.removeMusic
import com.chenxinzhimusic.refreshFlow
import com.chenxinzhimusic.service.MusicService.Companion.controller
import com.chenxinzhimusic.viewmodel.MusicViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlin.math.max
import kotlin.math.min
import kotlin.math.roundToInt
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.seconds
import kotlin.time.DurationUnit

@SuppressLint("UnnecessaryComposedModifier", "UnusedBoxWithConstraintsScope",
    "ConfigurationScreenWidthHeight"
)
@OptIn(ExperimentalSharedTransitionApi::class)
@Composable
fun MusicPlayerScreen(
    musicViewModel: MusicViewModel,
    onBack: () -> Unit
) {
    BackHandler {
        onBack()
    }
    val lifecycleOwner = LocalLifecycleOwner.current

    LaunchedEffect(Unit) {
        lifecycleOwner.repeatOnLifecycle(Lifecycle.State.RESUMED) {
            while (true) {
                musicViewModel.nowPlayCurrent = controller?.currentMediaItem
                val milliseconds =
                    controller?.duration?.takeIf { it != C.TIME_UNSET && it > 0 }?.milliseconds
                musicViewModel.duration =
                    milliseconds?.toInt(
                        DurationUnit.SECONDS
                    )
                        ?: 0
                val millisecondsD =
                    controller?.currentPosition?.takeIf { it != C.TIME_UNSET && it > 0 }?.milliseconds
                musicViewModel.position =
                    millisecondsD?.toInt(
                        DurationUnit.SECONDS
                    )
                        ?: 0
                musicViewModel.musicId = controller?.currentMediaItem?.mediaId

                delay(200)
            }
        }


    }




    Box(
        modifier = Modifier
            .background(Color.Gray)
            .fillMaxSize()
            .pointerInput(Unit) {
                awaitEachGesture {
                    awaitPointerEvent().let { it ->
                        it.changes.forEach {
                            it.consume()
                        }
                    }
                }
            }
    ) {
        // 背景图 + 动态模糊效果
        val rememberCoroutineScope = rememberCoroutineScope()
        if (musicViewModel.cover.isNotBlank()) {
            AsyncImage(
                model = musicViewModel.cover,
                contentDescription = null,
                contentScale = ContentScale.Crop,
                modifier = Modifier
                    .fillMaxSize()
                    .blur(radius = 25.dp),
                error = painterResource(R.drawable.ic_launcher_foreground)
            )
        }

        // 半透明遮罩增强前景可读性
        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(Color.Black.copy(alpha = 0.4f))
        )
        LookaheadScope {
            Column(
                horizontalAlignment = Alignment.CenterHorizontally,
                modifier = Modifier
                    .fillMaxSize()
                    .statusBarsPadding()
            ) {
                var showLyc by remember { mutableStateOf(false) }
                val title = remember {
                    movableContentWithReceiverOf<LookaheadScope> {
                        Text(
                            "${musicViewModel.nowPlayCurrent?.mediaMetadata?.title ?: "暂无歌曲"} - ${musicViewModel.nowPlayCurrent?.mediaMetadata?.artist ?: "暂无歌手"}",
                            color = Color.White,
                            lineHeight = 28.sp,
                            fontSize = 25.sp,
                            maxLines = 1,
                            modifier = Modifier
                                .animateBounds(this)
                                .basicMarquee()

                        )
                    }
                }


                // 封面旋转动画
                val rotation = remember { Animatable(0f) }

                LaunchedEffect(musicViewModel.isPlaying) {
                    if (musicViewModel.isPlaying) {
                        rotation.animateTo(
                            rotation.value + 360f,
                            infiniteRepeatable(tween(10000, easing = LinearEasing))
                        )
                    }
                }
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .weight(1f)
                        .padding(horizontal = 10.dp)
                ) {
                    IconButton(onClick = { onBack() }) {
                        Icon(
                            Icons.Outlined.ArrowBackIosNew,
                            null,
                            tint = Color.White,
                            modifier = Modifier
                                .size(20.dp)
                                .graphicsLayer {
                                    rotationZ = -90f
                                }
                        )
                    }
                }

                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .weight(7f)
                        .pointerInput(Unit) {
                            detectTapGestures {
                                showLyc = !showLyc
                            }
                        }, horizontalAlignment = Alignment.CenterHorizontally
                ) {

                    val ap by animateDpAsState(if (showLyc) 0.dp else 300.dp)
                    val w by animateFloatAsState(if (showLyc) 0f else 5f)

                    Box(
                        modifier = Modifier
                            .composed {
                                if (w > 0f) {
                                    weight(w)
                                } else {
                                    Modifier
                                }
                            }
                            .requiredSize(ap)
                            .graphicsLayer { rotationZ = musicViewModel.rotation.value }
                            .clip(CircleShape)
                            .background(Color.White.copy(alpha = 0.15f)),
                        contentAlignment = Alignment.Center
                    ) {
                        if (musicViewModel.cover.isNotBlank()) {
                            AsyncImage(
                                model = musicViewModel.cover,
                                contentDescription = "封面图",
                                contentScale = ContentScale.Crop,
                                modifier = Modifier
                                    .size(
                                        when {
                                            LocalConfiguration.current.screenWidthDp < 360 -> 240.dp
                                            LocalConfiguration.current.screenWidthDp < 480 -> 270.dp
                                            else -> 290.dp
                                        }
                                    )
                                    .clip(CircleShape),
                                error = painterResource(R.drawable.ic_launcher_foreground)
                            )
                        }
                    }

                    Column(
                        modifier = Modifier
                            .weight(1f)
                            .padding(horizontal = 50.dp),
                        horizontalAlignment = Alignment.CenterHorizontally,
                        verticalArrangement = Arrangement.SpaceBetween

                    ) {
                        LaunchedEffect(musicViewModel.musicId) {
                            if (musicViewModel.musicId != null) {
                                musicViewModel.lycList =
                                    Api.getLyc(musicViewModel.musicId!!)?.data?.lrclist?.map {
                                        it.time.toDouble() to it.lineLyric
                                    } ?: "[00:00.00] 暂无歌词"
                                        .split("\n").associate {
                                            (if (it.length > 8) {
                                                it.substring(1, 9)
                                            } else {
                                                it
                                            }) to if (it.length > 8) {
                                                it.substring(10)
                                            } else {
                                                ""
                                            }
                                        }
                                        .filter {
                                            it.key.isNotBlank()
                                        }
                                        .map {
                                            musicViewModel.convertToSeconds(it.key) to it.value
                                        }.toList()
                            }
                        }

                        if (showLyc) {
                            LaunchedEffect(musicViewModel.isPlaying) {
                                lifecycleOwner.repeatOnLifecycle(Lifecycle.State.RESUMED) {
                                    if (musicViewModel.isPlaying) {
                                        while (true) {
                                            val millisecondsD =
                                                controller?.currentPosition?.takeIf { it != C.TIME_UNSET && it > 0 }?.milliseconds
                                            musicViewModel.lycIndex =
                                                max(0, musicViewModel.lycList.filter {
                                                    (millisecondsD ?: 0.0.seconds) + 0.01.seconds >= it.first.seconds
                                                }
                                                    .lastIndex)
                                            delay(20)
                                        }
                                    }
                                }
                            }
                            val stateList = rememberLazyListState()
                            LaunchedEffect(musicViewModel.lycIndex) {
                                if (!stateList.isScrollInProgress) {
                                    stateList.animateScrollToItem(
                                        max(
                                            0,
                                            musicViewModel.lycIndex - 3
                                        )
                                    )

                                }

                            }
                            title()
                            LazyColumn(
                                modifier = Modifier
                                    .padding(top = 50.dp)
                                    .fillMaxSize(),
                                state = stateList,
                                horizontalAlignment = Alignment.CenterHorizontally
                            ) {
                                item {
                                    Spacer(modifier = Modifier.height(50.dp))
                                }
                                items(musicViewModel.lycList.size) {
                                    val bool = it == musicViewModel.lycIndex
                                    val lycColor by animateColorAsState(
                                        if (bool) Color(
                                            0xffffffff
                                        ) else Color(0xb1ffffff)
                                    )
                                    val focusRequester = remember { FocusRequester() }
                                    val lycFontSize by animateFloatAsState(if (bool) 23f else 20f)
                                    LaunchedEffect(bool) {
                                        try {
                                            if (bool) {
                                                focusRequester.requestFocus()
                                            }
                                        }catch (_: Exception){
                                        }
                                    }
                                    val textMeasurer = rememberTextMeasurer()
                                    val density = LocalDensity.current

                                    // 测量文本宽度，带样式
                                    val textLayoutResult = textMeasurer.measure(
                                        text = musicViewModel.lycList[it].second,
                                        style = androidx.compose.ui.text.TextStyle(fontSize = 23.sp),
                                        maxLines = 1
                                    )
                                    var containerWidth by remember { mutableFloatStateOf(0f) }
                                    val textWidthPx = textLayoutResult.size.width.toFloat()
                                    val velocityDpPerSecond = with(density) {
                                        val toPx = 50.0000.dp.toPx()
                                        (max(textWidthPx + toPx - containerWidth, 0.0000f) / max(
                                            0.0001, (try {
                                                musicViewModel.lycList[it + 1].first
                                            } catch (_: Exception) {
                                                musicViewModel.durationM / 1000.00000
                                            } - musicViewModel.lycList[it].first) - 0.200000
                                        )).toFloat().toDp()
                                    }
                                    val b = try {
                                        musicViewModel.lycList[it].first == musicViewModel.lycList[it + 1].first
                                    } catch (_: Exception) {
                                        false
                                    }
                                    var press by remember { mutableStateOf(false) }
                                    var showPlayer by remember { mutableStateOf(false) }
                                    val showPlayerA by animateFloatAsState(
                                        if (showPlayer) 1f else 0f
                                    )
                                    LaunchedEffect(press) {
                                        if (press) {
                                            showPlayer = true
                                        } else {
                                            delay(1500)
                                            showPlayer = false
                                        }


                                    }
                                    Box(
                                        contentAlignment = Alignment.CenterStart,
                                        modifier = Modifier.pointerInput(Unit) {
                                            awaitEachGesture {
                                                var event: PointerEvent
                                                do {
                                                    event = awaitPointerEvent()
                                                    press = true
                                                } while (!event.changes.fastAll {
                                                        it.changedToUpIgnoreConsumed()
                                                    })
                                                press = false

                                            }
                                        }) {
                                        Text(
                                            musicViewModel.lycList[it].second,
                                            color = lycColor,
                                            fontSize = lycFontSize.sp,
                                            style = androidx.compose.ui.text.TextStyle(fontSize = lycFontSize.sp),
                                            maxLines = 1,
                                            textAlign = TextAlign.Center,
                                            modifier = Modifier
                                                .fillMaxWidth()
                                                .onPlaced { coordinates ->
                                                    containerWidth =
                                                        coordinates.size.width.toFloat() // 单位 px
                                                }
                                                .basicMarquee(
                                                    animationMode = if (b
                                                    ) MarqueeAnimationMode.Immediately else MarqueeAnimationMode.WhileFocused,
                                                    velocity = if (b) Velocity else velocityDpPerSecond
                                                )
                                                .focusRequester(focusRequester)
                                                .focusable(),
                                        )

                                        Icon(
                                            Icons.Default.PlayCircleOutline,
                                            contentDescription = null,
                                            tint = lycColor.copy(alpha = showPlayerA),
                                            modifier = Modifier
                                                .size(20.dp)
                                                .offset(
                                                    x = with(density){
                                                        containerWidth.toDp()
                                                    }
                                                )
                                                .pointerInput(Unit) {
                                                    detectTapGestures { _ ->
                                                        if (showPlayer) {
                                                            controller?.seekTo((musicViewModel.lycList[it].first * 1000).toLong())
                                                        }
                                                    }
                                                },
                                        )

                                    }
                                    Spacer(modifier = Modifier.height(20.dp))
                                }
                                item {
                                    Spacer(modifier = Modifier.height(50.dp))
                                }
                            }

                        } else {
                            Spacer(modifier = Modifier.height(50.dp))
                            title()
                        }

                    }


                }
                var makeText: Toast? = null

                Spacer(Modifier.height(16.dp))
                Column(modifier = Modifier.weight(3.5f)) {

                    Spacer(Modifier.height(40.dp))

                    // 进度条
                    Column(
                        modifier = Modifier
                            .padding(horizontal = 50.dp)
                    ) {
                        MusicLinearProgressIndicator(
                            musicViewModel.duration,
                            musicViewModel.position
                        ) {
                            controller?.seekTo((musicViewModel.duration * it * 1000).toLong())
                        }
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.SpaceBetween
                        ) {
                            Text(formatTime(musicViewModel.position), color = Color.White)
                            Text(formatTime(musicViewModel.duration), color = Color.White)
                        }
                    }


                    // 控制按钮
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(70.dp),
                        horizontalArrangement = Arrangement.SpaceEvenly,
                        verticalAlignment = Alignment.Top
                    ) {
                        IconButton(onClick = {

                            controller?.seekToPreviousMediaItem()
                        }) {
                            Icon(
                                Icons.Outlined.SkipPrevious,
                                null,
                                tint = Color.White,
                                modifier = Modifier.size(36.dp)
                            )
                        }
                        IconButton(onClick = {

                            if (musicViewModel.isPlaying) {
                                controller?.pause()
                            } else {
                                controller?.play()
                            }
                        }) {
                            Icon(
                                if (musicViewModel.isPlaying) Icons.Outlined.Pause else Icons.Outlined.PlayArrow,
                                null,
                                tint = Color.White,
                                modifier = Modifier.size(48.dp)
                            )
                        }
                        IconButton(onClick = {

                            controller?.seekToNextMediaItem()
                        }) {
                            Icon(
                                Icons.Outlined.SkipNext,
                                null,
                                tint = Color.White,
                                modifier = Modifier.size(36.dp)
                            )
                        }

                    }
                    var context = LocalContext.current
                    var nowI by remember { mutableIntStateOf(0) }
                    var isLove by remember { mutableStateOf(false) }
                    LaunchedEffect(isLove, musicViewModel.musicId) {
                        with(context) {
                            val music = getMusic<PlayList?>(loveKey)
                            music?.let {
                                isLove =
                                    it.musicList.map { it.musicId }.contains(musicViewModel.musicId)
                            }
                        }
                    }
                    val loveAni by animateColorAsState(if (isLove) Color.Red else Color.White)
                    LaunchedEffect(Unit) {
                        while (controller == null) {
                            delay(100)
                        }
                        controller?.let {
                            nowI = when {
                                it.shuffleModeEnabled -> 2
                                it.repeatMode == Player.REPEAT_MODE_OFF -> 0
                                it.repeatMode == Player.REPEAT_MODE_ONE -> 1
                                it.repeatMode == Player.REPEAT_MODE_ALL -> 3
                                else -> 0

                            }
                        }
                    }
                    val mutex = remember { Mutex() }
                    val pairs = listOf(
                        Icons.AutoMirrored.Filled.QueueMusic to {
                            rememberCoroutineScope.launch {
                                mutex.withLock {
                                    makeText?.cancel()
                                    makeText =
                                        Toast.makeText(context, "顺序播放", Toast.LENGTH_SHORT)
                                    makeText?.show()
                                    controller?.repeatMode = Player.REPEAT_MODE_OFF
                                    controller?.shuffleModeEnabled = false
                                }
                            }
                        },

                        Icons.Default.RepeatOne to {
                            rememberCoroutineScope.launch {
                                mutex.withLock {
                                    makeText?.cancel()
                                    makeText =
                                        Toast.makeText(context, "单曲循环", Toast.LENGTH_SHORT)
                                    makeText?.show()
                                    controller?.repeatMode = Player.REPEAT_MODE_ONE
                                    controller?.shuffleModeEnabled = false
                                }
                            }


                        },
                        Icons.Default.Shuffle to {
                            rememberCoroutineScope.launch {
                                mutex.withLock {
                                    makeText?.cancel()
                                    makeText =
                                        Toast.makeText(context, "随机播放", Toast.LENGTH_SHORT)
                                    makeText?.show()

                                    controller?.repeatMode = Player.REPEAT_MODE_ALL
                                    controller?.shuffleModeEnabled = true
                                }
                            }

                        },
                        Icons.Default.Repeat to {
                            rememberCoroutineScope.launch {
                                mutex.withLock {
                                    makeText?.cancel()
                                    makeText =
                                        Toast.makeText(context, "列表循环", Toast.LENGTH_SHORT)
                                    makeText?.show()
                                    controller?.repeatMode = Player.REPEAT_MODE_ALL
                                    controller?.shuffleModeEnabled = false
                                }
                            }
                        }
                    )
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(25.dp),
                        horizontalArrangement = Arrangement.SpaceEvenly,
                        verticalAlignment = Alignment.Top
                    ) {

                        IconButton(onClick = {
                            rememberCoroutineScope.launch {
                                with(context) {
                                    musicViewModel.musicId?.let {
                                        if (isLove) {
                                            removeMusic(loveKey, it)
                                            mutex.withLock {
                                                makeText?.cancel()
                                                makeText =
                                                    Toast.makeText(
                                                        context,
                                                        "你不爱我了💔",
                                                        Toast.LENGTH_SHORT
                                                    )
                                                makeText?.show()

                                            }
                                        } else {
                                            val musicInfo = MusicInfo(
                                                musicViewModel.musicId ?: "",
                                                musicViewModel.nowPlayCurrent?.mediaMetadata?.title?.toString()
                                                    ?: "",
                                                musicViewModel.nowPlayCurrent?.mediaMetadata?.artist?.toString()
                                                    ?: "",
                                                musicViewModel.nowPlayCurrent?.mediaMetadata?.artworkUri?.toString()
                                                    ?: "",
                                                musicViewModel.duration,
                                                0,
                                                "",
                                                musicViewModel.nowPlayCurrent?.mediaMetadata?.albumTitle?.toString()
                                                    ?: ""

                                            )
                                            mutex.withLock {
                                                makeText?.cancel()
                                                makeText =
                                                    Toast.makeText(
                                                        context,
                                                        "感谢喜欢♥️",
                                                        Toast.LENGTH_SHORT
                                                    )
                                                makeText?.show()

                                            }
                                            addToLove(
                                                musicInfo
                                            )
                                        }
                                        isLove = !isLove
                                        refreshFlow.emit(Unit)
                                    }
                                }

                            }

                        }) {
                            Icon(
                                Icons.Filled.Favorite,
                                null,
                                tint = loveAni,
                                modifier = Modifier.size(30.dp)
                            )
                        }
                        IconButton(onClick = {
                            val i = nowI + 1
                            nowI = if (i >= pairs.size) 0 else i
                            pairs[nowI].second()

                        }) {
                            Icon(
                                pairs[nowI].first,
                                null,
                                tint = Color.White,
                                modifier = Modifier.size(30.dp)
                            )
                        }


                    }
                }
            }
        }
    }
}

@SuppressLint("UnusedBoxWithConstraintsScope")
@Composable
fun MusicLinearProgressIndicator(
    duration: Int, position: Int, seek: (Float) -> Unit
) {
    var useInner by rememberSaveable {
        mutableStateOf(
            false
        )
    }
    val processC by rememberSaveable(duration, position) {
        mutableFloatStateOf(
            if (duration > 0) {
                position.toFloat() / duration.toFloat()
            } else {
                0f
            }
        )
    }
    var process by rememberSaveable {
        mutableFloatStateOf(0F)
    }
    LaunchedEffect(processC) {
        if (!useInner) {
            process = processC
        }
    }


    BoxWithConstraints(contentAlignment = Alignment.TopCenter) {
        val processWidth = constraints.maxWidth.toFloat()
        val processWidthUse = min(processWidth * process, processWidth)
        Canvas(
            Modifier
                .fillMaxWidth()
                .height(8.dp)
                .clip(RoundedCornerShape(10.dp))


        ) {
            drawRect(Color(0x33888888), size = Size(processWidth, size.height))
            drawRect(Color(0xE6d33a31), size = Size(processWidthUse, size.height))
        }
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(20.dp)
                .pointerInput(Unit) {
                    detectTapGestures {
                        seek(it.x / processWidth)
                        useInner = false

                    }
                }
        ) {

            val y = with(LocalDensity.current) {
                -6.dp.toPx().toInt()
            }
            Canvas(
                Modifier
                    .offset {
                        val fl = 20.dp.toPx() / 2
                        IntOffset(
                            -fl.roundToInt() + processWidthUse.roundToInt(), y
                        )
                    }
                    .size(20.dp)
                    .pointerInput(Unit) {
                        detectDragGestures(onDragStart = {
                            useInner = true

                        }, onDragEnd = {
                            useInner = false
                            seek(process)

                        }) { change: PointerInputChange, dragAmount: Offset ->
                            useInner = true
                            process += (dragAmount.x / processWidth)
                        }

                    }
            ) {
                drawCircle(Color(0xffd33a31))
            }
        }


    }
}

private fun formatTime(seconds: Int): String {
    val mins = (seconds / 60)
    val secs = (seconds % 60)
    return "%02d:%02d".format(mins, secs)
}
